package com.study.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.study.beans.User;
import com.study.service.UserService;

@RestController
public class UserController {

	@Autowired
	private UserService userService;
	
	@Autowired
	private DiscoveryClient client;
	
	@PostMapping("/user/add")
	public boolean add(@RequestBody User user) {
		return userService.addUser(user);
	}
	
	@GetMapping("/user/get/{id}")
	//在服务端做熔断处理
	//一旦调用服务方法失败并抛出了错误信息后，会自动调用@HystrixCommand标注好的fallbackMethod调用类中的指定方法
	@HystrixCommand(fallbackMethod = "processHystrix_Get")
	public User get(@PathVariable("id") Integer id) {
		User user = userService.findById(id);
		if(user == null) {
			throw new RuntimeException(id+"没有对应的记录");
		}
		return user;
	}
	
	@GetMapping("/user/list")
	public List<User> list() {
		return userService.findAll();
	}
	
	@GetMapping("/user/discovery")
	public Object discovery()
	{
		List<String> list = client.getServices();
		System.out.println("**********" + list);

		List<ServiceInstance> srvList = client.getInstances("CLOUD-PROVIDER");
		for (ServiceInstance element : srvList) {
			System.out.println(element.getServiceId() + "\t" + element.getHost() + "\t" + element.getPort() + "\t"
					+ element.getUri());
		}
		return this.client;
	}
	
	/**
	 * 熔断器的回调函数
	 * <p>Title: processHystrix_Get<／p>
	 * <p>Description: <／p>
	 * @param id
	 * @return
	 */
	public User processHystrix_Get(@PathVariable("id") Integer id)
	{
		return new User().setId(id).setName("该ID：" + id + "没有没有对应的信息,null--@HystrixCommand")
				.setAddress("no this database in MySQL");
	}
}
